package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.common.result.JsonResult;
import cn.itsource.ymcc.common.result.PageList;
import cn.itsource.ymcc.config.AliPayConfig;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.dto.PayDto;
import cn.itsource.ymcc.query.PayOrderQuery;
import cn.itsource.ymcc.service.IPayOrderService;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/payOrder")
public class PayOrderController {

    @Autowired
    public IPayOrderService payOrderService;
    @Autowired
    private AliPayConfig aliPayConfig;

    @PostMapping("/ZFBCallback")
    public String ZFBCallback(HttpServletRequest request){
        try {
            //我们要将数据给全部取出来
            Map<String, String[]> parameterMap = request.getParameterMap();
            //支付宝的回传参数
            Map<String, String> parameters = new HashMap<>();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                parameters.put(entry.getKey(), entry.getValue() != null ? entry.getValue()[0] : null);
            }
            //模拟数据数据篡改
//            parameters.put("out_trade_no","66666");
            //二次验签
            Boolean aBoolean = Factory.Payment.Common().verifyNotify(parameters);
            if(aBoolean){
                //付款后的结果的处理
                payOrderService.resultHandle(parameters);
                return "success";
            }else {
                return "failure";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/apply")
    public JsonResult apply(@RequestBody PayDto payDto){
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>()
                .eq(PayOrder::getOrderNo, payDto.getOrderNo()));
        switch (payDto.getPayType()){
            case 1:
                String pay = aliPayConfig.toPay(one.getSubject(),payDto.getOrderNo(),one.getAmount().toString(),payDto.getCallUrl());
                //pay就支付宝的付款地址
                return JsonResult.success().setData(pay);
            case 2:
                //微信
                break;
            case 3:
                //银联
                break;
            default:
                break;
        }
        return JsonResult.error("支付异常");
    }

    @GetMapping("/checkPayOrder/{orderNo}")
    public JsonResult checkPayOrder(@PathVariable("orderNo")String orderNo){
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>()
                .eq(PayOrder::getOrderNo, orderNo));
        if(one == null){
            return JsonResult.error("支付的未生成");
        }
        return JsonResult.success();
    }

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody PayOrder payOrder){
        if(payOrder.getId()!=null){
            payOrderService.updateById(payOrder);
        }else{
            payOrderService.save(payOrder);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        payOrderService.removeById(id);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success().setData(payOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.success().setData(payOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody PayOrderQuery query){
        Page<PayOrder> page = new Page<PayOrder>(query.getPageNo(), query.getPageSize());
        page = payOrderService.page(page);
        return JsonResult.success().setData(new PageList<PayOrder>(page.getTotal(), page.getRecords()));
    }
}
